package com.bstek.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.jdbc.support.JdbcUtils;

import com.bstek.common.config.DataSourceConfig;
import com.bstek.datasource.bean.DataSourceInfo;

public class MultipleJdbcTemplate {
	
	private static Map<Integer,String> types = new HashMap<Integer, String>();
	
	static {
		try {
			Class<?> clazz = Class.forName("java.sql.Types");
			Field[] declaredFields = clazz.getDeclaredFields();
	        for (Field field : declaredFields) {
	            field.setAccessible(true);
	            if( Modifier.isStatic(field.getModifiers())){
	            	types.put(field.getInt(clazz), field.getName());
	            }
	        }
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static List<Map<String,String>> getDatabaseTables(String code) {
		List<Map<String,String>> tables = new ArrayList<Map<String,String>>();
		Connection conn = null;
		ResultSet rs = null;
		try {
			conn = buildConnection(code);
			DatabaseMetaData metaData = conn.getMetaData();
			String dbName = conn.getCatalog();
			String schema = conn.getSchema();
			rs = metaData.getTables(dbName, schema, "%", new String[] { "TABLE", "VIEW" });
			while (rs.next()) {
				Map<String,String> table = new HashMap<String, String>();
				table.put("name",rs.getString("TABLE_NAME"));
				table.put("type",rs.getString("TABLE_TYPE"));
				tables.add(table);
			}
			
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeConnection(conn);
		}
		return tables;
	}
	
	public static NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(Connection conn) {
		DataSource dataSource = new SingleConnectionDataSource(conn, false);
		NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
		return jdbcTemplate;
	}
	
	public static Connection buildConnection(String code) {
		DataSourceInfo info = DataSourceConfig.getDataSourceInfo(code);
		try {
			String username = info.getUserName();
			String password = info.getPassword();
			String driver = info.getDriverClassName();
			String url = info.getUrl();
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
